import { defineStore } from "pinia";
import { Names } from "./store-namespace";
import { AdminInfo } from "./types/type";
import { ADMIN_INFO } from "./constant/cacheKey"; //sessionStorage的key值
import { _get, _post, _put, _delete, http } from "@/utils/axios";
import { adminApis } from "@/api/backend/index";
import { Apis } from "@/api/frontend";
import { ElNotification } from "element-plus"; //处理导航信息

export const useAdminInfo = defineStore(Names.adminInfo, {
  state: (): any => {
    return {
      userId: 0, //用户id
      userName: "", //用户名
      nickName: "", //登录账号名称
      avatar: "", //头像
      loginDate: "", //最近一次登录时间
      token: "",
      refreshToken: "",
      companyid: null,
      super: true, // 是否是superAdmin，用于判定是否显示终端按钮等，不做任何权限判断
    };
  },
  getters: {},
  actions: {
    //替换整个admin用户数据
    dataFill(state: any) {
      this.$state = { ...this.$state, ...state };
    },
    removeToken() {
      this.token = "";
      this.refreshToken = "";
    },
    setToken(token: string, type: "token" | "refreshToken") {
      this[type] = token;
    },
    getToken(type: "auth" | "refresh" = "auth") {
      return type === "auth" ? this.token : this.refreshToken;
    },
    /**
     * 登录后
     * 无论成功失败 form.loading = false
     * 替换整个admin用户数据 adminInfo.dataFill(res.data.userinfo)
     * 跳转路由 router.push({ path: res.data.routePath })
     */
    login(data: object = {}) {
      return new Promise((resolve, reject) => {
        _post(adminApis.login, data, "json", "")
          .then((res: any) => {
            let BToken = "Bearer " + res.data.token;
            this.token = BToken;
            resolve(res as any);
          })
          .catch((res) => {
            reject(res);
          });
      });
    },
    /**
     * 退出登录需携带数据 refresh_token: adminInfo.getToken('refresh'),
     * 退出登录后在storage.ts中调用Local对象中remove方法清除缓存的localstorage的admininfo信息
     *  Local.remove(ADMIN_INFO)
     * 刷新 router.go(0)
     */
    logout() {},
    //获取个人信息
    getAdminInfo() {
      return new Promise((resolve, reject) => {
        _get(adminApis.getInfo, {}, "", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log("401 userId=0");

            if (err.data.code === 401) {
              //token过期就清空
              this.$state = {
                userId: 0, //用户id
                userName: "", //用户名
                nickName: "", //登录账号名称
                avatar: "", //头像
                loginDate: "", //最近一次登录时间
                token: "",
                refreshToken: "",
                companyid: null,
                super: true, // 是否是superAdmin，用于判定是否显示终端按钮等，不做任何权限判断
              };
            }
            reject(err);
          });
      });
    },
    //获取路由信息
    getRouters() {
      return new Promise((resolve, reject) => {
        _get(adminApis.getRouters, {}, "", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
  //数据可持久化 "pinia-plugin-persistedstate"
  /**
   * key: 'ADMIN_INFO',//设置存储的key
   * storage: localStorage, //默认是存在localStorage
   * 默认所有 state 都会进行缓存,
   * 如果你不想所有的数据都持久化存储，
   * 那么可以通过 paths 指定要长久化的字段，
   * 其余的字段则不会进行长久化 paths: ['id'],//指定要长久化的字段
   */
  persist: {
    key: ADMIN_INFO,
  },
});
